import {ref,unref,nextTick} from "vue";

export const cacheRoutes = ref([]);


export const pushCacheRoute = (route)=>{
    let index = cacheRoutes.value.findIndex((item)=>{
        return item == route;
    });
    if(index < 0){
        cacheRoutes.value.push(route)
    }
};

export const reduceCacheRoute = (route)=>{
    let index = cacheRoutes.value.findIndex((item)=>{
        return item == route;
    });
    if(index >= 0){
    cacheRoutes.value.splice(index,1);
    }
}

export const clearCacheRoute = ()=>{
    cacheRoutes.value = [];
}


/**
 * 下换线转驼峰
 * @param {*} str 
 * @returns 
 */
function underlineToCamel(str) {
    str = str.replace("/","");
    if(!str){
        return "";
    }
   
  let result = str.replace(/_(\w)/g, function (all, letter) {
    return letter.toUpperCase();
  });
  return result.charAt(0).toUpperCase() + result.slice(1);
}


function existInMenus(path,menuList){
    path = path.replace("/","");
    let flag = false;
    unref(menuList).forEach((item)=>{
        if(item.child && item.child.length > 0){
            let cTarget = item.child.find((cItem)=>{
                return cItem.url == path;
            });
           cTarget && (flag = true);
        }else{
            // console.log(item.url,path)
            if(item.url == path){
                flag = true;
            }
        };
    });
    return flag;
};

/**
 * 缓存路由
 * @param {*} to 
 * @param {*} from 
 * @param {*} menuList 
 */
function cacheRoute(to,from,menuList){
    // console.log(to)
    let toPath = to.path;
    let fromPath = from.path;
    let toName = to.name || underlineToCamel(toPath);
    let fromName = from.name || underlineToCamel(fromPath);
    if(from.meta && from.meta.to){  //缓存数组存在的话，按照缓存数组做
      let fromCanCanche =  from.meta.to.map((item)=>underlineToCamel(item));
    //   console.log(fromCanCanche)
       let toIndex = fromCanCanche.indexOf(toName);
       if(toIndex >-1){
        pushCacheRoute(fromName);
       };
    }else{  

    }; 
};

/**
 * 路由结束后按照条件清除缓存
 * @param {*} to 
 * @param {*} from 
 * @param {*} menuList 
 */
function uncacheRoute(to,from,menuList){
    let toPath = to.path;
    if(existInMenus(toPath,menuList)){  //如果是根据右侧菜单切换，缓存页面设置为空
        nextTick(()=>{
            cacheRoutes.value = [];
        })
       
    }else{
       let targetIndex = cacheRoutes.value.indexOf(underlineToCamel(toPath));
       if(targetIndex >=0){
          nextTick(()=>{
            cacheRoutes.value.splice(targetIndex,1);
          })
       };

    };
};

/**
 * 生成路由缓存策略
 * @param {*} router 
 * @param {*} menuList 
 * @returns 
 */
export const CreateCacheRoutes =(router,menuList)=>{
    router.beforeEach((to,from)=>{
        cacheRoute(to,from,menuList);
        return true;
    });

    router.afterEach((to,from)=>{
        uncacheRoute(to,from,menuList);
    });

    return cacheRoutes;
};